const http = require("http")
const url = require('url');
const { httpReadFile, readFile, htmlReadWithData, writeFile } = require("./utils/file")
const server = http.createServer()
server.listen(3000, function () {
    console.log("留言板项目启动成功");
})

server.on("request", function (request, response) {
    const { pathname, query } = url.parse(request.url, true)
    if (pathname === "/") {
        readFile("./data.json").then(res => {
            htmlReadWithData("./views/index.html", response, JSON.parse(res.toString()))
        })

    } else if (pathname.startsWith("/node_modules")) {
        httpReadFile("." + request.url, response)

    } else if (pathname === "/add") {
        httpReadFile("./views/add.html", response)
    } else if (pathname === "/post") {

        readFile("./data.json").then(res => {
            const list = JSON.parse(res)
            query.time = "2020-11-03"
            list.push(query)
            return list
        }).then((list) => {

            writeFile("./data.json", JSON.stringify(list)).then(res => {
                response.statusCode = 302;
                response.setHeader("Location", "/")
                response.end()
            })
        })

        // console.log(list)

    }
    else {
        httpReadFile("./views/404.html", response)
    }
})
